import { Group, Vector3 } from "three";
import MatCap from "@/materials/matcap.js";
import { Body, SHAPE_TYPES } from "cannon-es";

const colors = ["blue", "red", "yellow", "red", "brown"];

export default class Bricks {
  constructor(physics) {
    this.physics = physics;
    this.models = [];

    this.main = new Group();
    this.shadows = [];
    this.meshes = [];

    this.physicsBodies = [];

  }

  add(resources) {
    this.resources = resources;
  }

  build() {
    const modelBricks = this.resources["model-bricks"].scene;
    this.models.push(...modelBricks.children);

    const min = 30;
    const max = 60;
    const nums = 30;

    for (let i = 0; i < nums; i++) {
      const distance = Math.random() * (max - min) + min;
      const angle = Math.random() * Math.PI * 2;

      const position = new Vector3(
        Math.cos(angle) * distance,
        Math.sin(angle) * distance,
        10
      );
      const brick = this.createBrick(position);
      const color = colors[Math.round(Math.random() * 3)];
      brick.material = MatCap(this.resources[`matcap-${color}`]);
      this.meshes.push(brick);
      this.main.add(brick);

      const brickPhysics = this.physics.createBody({ mesh: brick, shapeType: SHAPE_TYPES.BOX, mass: 10 });
      brickPhysics.wakeUp();
      this.physicsBodies.push(brickPhysics);
    }
    this.models.forEach(e => {
      e.parent?.remove(e);
    });
  }

  createBrick(position) {
    const index = Math.round(Math.random());
    const scale = Math.random() * .8 + .8;
    const brick = this.models[index].clone();
    brick.position.copy(position);
    brick.scale.set(scale, scale, scale);
    return brick;
  }

  update() {
    this.physicsBodies.forEach((e, i) => {
      const mesh = this.meshes[i];
      mesh.position.set(e.position.x, e.position.y, e.position.z);
      mesh.quaternion.set(e.quaternion.x, e.quaternion.y, e.quaternion.z, e.quaternion.w);
    });
  }
}